import { Component, OnInit, AfterViewInit, ViewChild, OnDestroy } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { Router, ActivatedRoute } from '@angular/router';

import { BehaviorSubject } from 'rxjs';
import { debounceTime, distinctUntilChanged } from 'rxjs/operators';

import { orderStateArrs, machineInspectionArrs } from '../love-recyc-manage.pipe';
import { LoveOrderManageService } from '../love-order-manage.service';

@Component({
  selector: 'app-inspection-machine-list',
  templateUrl: './inspection-machine-list.component.html',
  styleUrls: ['./inspection-machine-list.component.scss']
})
export class InspectionMachineListComponent implements OnInit, OnDestroy {
  @ViewChild('expnoRef') expnoRef: any;
  // @ViewChild('expnoRefHidden') expnoRefHidden: any;
  @ViewChild('userInfoRef') userInfoRef: any;

  // 路由缓存恢复时
  static updateCache: any = null;
  isCollapse: boolean = true;

  seachParams: any = {
    okey: '', // 订单号
    expno: '', // 快递单号
    phoneCode: '', // 机器编号
    phoneSerialNumber: '', // 机器序列号
    umname: '', // 机型
    category: '', // 品类
    lnker: '', // 寄件人
    checkStatus: '', // 验机状态
    checkId: '', // 验机工程师[OLD]
    checkName: '', // 验机工程师name
    orderWay: '', // 下单方式：1、估价下单  2、批量下单
  };

  // 验机状态
  machineStateOptions: any = [...machineInspectionArrs];

  // 订单状态options
  orderStateOptions: any = [...orderStateArrs];
  orderStateSelected: any = [];

  // 验机工程师options
  masterWorkerOptions: any = [];
  workerSelected: any = [];

  // 验机状态Array Selected
  checkStatusSelected: any  =[];

  tableParams: any = {
    tableLoading: false,
    page: 1,
    pageSize: 20,
    total: 0
  };
  tableData: any = [];

  // 用户信息
  modalUserId: any = null;

  // 机器编码防抖
  searchCodeChange$ = new BehaviorSubject('');

  constructor(
    private message: NzMessageService,
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private services: LoveOrderManageService
  ) { }

  ngOnInit() {
    InspectionMachineListComponent.updateCache = () => {
      // 订单号input 聚焦
      setTimeout(() => {
        this.expnoRef.nativeElement.focus();
      }, 50);
      // this.getWorkerData();
      this.loadTable();
    }

    // 订单号input 聚焦
    setTimeout(() => {
      this.expnoRef.nativeElement.focus();
    }, 50);
    // this.getWorkerData();
    this.loadTable();

    // 机器编码输入防抖(扫码枪)
    this.searchCodeChange$
      .pipe(debounceTime(500))
      .subscribe(data => {
        if (data.includes('i5.cn')) {
          let startIndex = data.lastIndexOf('/');
          let scanStr = data.substring(startIndex + 1);

          this.seachParams.phoneCode = scanStr;
          this.tableParams.page = 1;
          this.loadTable();
        }
      });
  }

  ngOnDestroy() {
    this.searchCodeChange$.unsubscribe();
  }

  // 查询验机师List
  async getWorkerData() {
    const res: any = await this.services.getMasterWorkerList();
    if (res.code == 0) {
      this.masterWorkerOptions = res.data || [];
    } else {
      this.masterWorkerOptions = [];
    }
  }

  // Table List
  async loadTable() {
    try {
      let params = {
        ...this.seachParams,
        ostat: this.orderStateSelected.join(','), // 订单状态
        page: this.tableParams.page,
        pageSize: this.tableParams.pageSize
      }
      this.tableParams.tableLoading = true;
      const res: any = await this.services.getOrderList(params);
      this.tableParams.tableLoading = false;

      if (res.code == 0) {
        const { list, total } = res.data || {};
        this.tableData = list || [];
        this.tableParams.total = total || 0;
      } else {
        this.message.error(res.message);
      }
    } catch (error: any) {
      this.tableParams.tableLoading = false;
      this.message.error(error);
    }
  }

  // 验机师change
  workerChange(result: any) {
    this.seachParams.checkId = result.join(',');
  }

  seachData() {
    this.tableParams.page = 1;
    this.loadTable();
  }
  resetData() {
    for (let key in this.seachParams) {
      this.seachParams[key] = '';
    }
    this.workerSelected = [];

    this.orderStateSelected = [];
    this.tableParams.page = 1;
    this.loadTable();
  }

  // 爱思用户信息 Modal
  userInfoPreview(item: any) {
    this.modalUserId = item.user_id;
    this.userInfoRef.isVisible = true;
  }

  // 物流单号Tab事件
  dealScanInput() {
    if (this.seachParams.expno) {
      this.tableParams.page = 1;
      this.loadTable();
    }
  }

  // 当前页码改变时的回调函数
  onPageIndexChange(index: number) {
    this.tableParams.page = index;
    this.loadTable();
  }
  // 页数改变时的回调函数
  onPageSizeChange(sizeNum: number) {
    this.tableParams.pageSize = sizeNum;
    this.loadTable();
  }

  // search mutiple
  multipleChange(val: any, key: string) {
    this.seachParams[key] = val?.length ? val.join(',') : '';
  }

  // 机器编码Change
  searchCodeChange(val: any) {
    this.searchCodeChange$.next(val);
  }
}
